package org.singledog.form.builder.parser.freemarker.directions;

import freemarker.core.Environment;
import freemarker.template.*;
import freemarker.template.utility.DeepUnwrap;
import org.apache.commons.lang3.StringUtils;
import org.singledog.form.builder.ComponentType;
import org.singledog.form.builder.MagicConstants;
import org.singledog.form.builder.parser.ComponentParserRegistry;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class DatagridBuilderTemplateDirectiveModel implements TemplateDirectiveModel {

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        if (CollectionUtils.isEmpty(params)) {
            throw new TemplateModelException("this directive need params !");
        }

        ComponentType type = ComponentType.datagrid;
        String code = null;

        Iterator paramIter = params.entrySet().iterator();
        Map<String, Object> viewData = new HashMap<>();

        while (paramIter.hasNext()) {
            Map.Entry ent = (Map.Entry) paramIter.next();

            String paramName = (String) ent.getKey();
            TemplateModel paramValue = (TemplateModel) ent.getValue();
            if (paramValue == null) {
                continue;
            }

            Object val = DeepUnwrap.unwrap(paramValue);

            switch (paramName) {
                case MagicConstants.TYPE:
                    type = ComponentType.valueOf((String) val);
                    break;
                case MagicConstants.CODE:
                    code = (String) val;
                default:
                    viewData.put(paramName, val);
            }

            if (StringUtils.isEmpty(code)) {
                throw new TemplateModelException(
                        "No param code found !");
            }
        }

        Writer out = env.getOut();
        String html = ComponentParserRegistry
                .getComponentParser(type)
                .parseView(code).toHtml(null, viewData);
        out.write(html);
        if (body != null) {
            body.render(out);
        }

    }
}
